import React, { Component } from 'react';

export default class DragDiv extends Component {
    constructor(props) {
        super(props);
        this.state = {
            autoSave: false,
            visible: false,
            hasSeleted: false,
            saving: false,
            notify: null,
            editState: 'select'
        }
    }
    componentDidMount() {
        document.body.addEventListener('mousemove', this.onMouseMove.bind(this));
        document.body.addEventListener('mouseup', this.onMouseUp.bind(this));
    }
    onMouseDown(e) {
        let positionLeft = this.rootRef.offsetLeft;
        let positionTop = this.rootRef.offsetTop;
        this.dragGap = {
            gapX: e.clientX - positionLeft,
            gapY: e.clientY - positionTop
        }
        this.startDrag = true;
    }
    onMouseUp() {
        this.startDrag = false;
    }
    onMouseMove(e) {
        if (!this.startDrag) {
            return;
        }
        let left = e.clientX - this.dragGap.gapX;
        let top = e.clientY - this.dragGap.gapY;
        this.rootRef.style.left = left + 'px';
        this.rootRef.style.top = top + 'px';
        this.rootRef.style.right = 'auto';
        this.rootRef.style.bottom = 'auto';
        this.props.onMoveEnd?.({ left, top })
    }
    componentWillUnmount() {
        document.body.removeEventListener('mousemove', this.onMouseMove);
        document.body.removeEventListener('mouseup', this.onMouseMove);
    }
    render() {
        return <div ref={ref => this.rootRef = ref} {...this.props} onMouseDown={this.onMouseDown.bind(this)}>

        </div>
    }
}